package com.ruoyi.common.utils.sms;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chmj
 * @version V1.0
 * @Package com.ruoyi.common.utils.sms
 * @Copyright 2022/10/31 10:19 汇博医疗股份有限公司
 */
@Slf4j
public class SmsUtils {

    private static String accessKeyId = "LTAI5tJBNG8xHYGV7arJKyLH"; //签名
    private static String accessKeySecret = "Ih2a3kMwO4ym7MEts5hmQthQTPnUln"; //模板

    private static String smsSignName = "XP西畔"; //签名
    private static String templateCode = "SMS_256736479"; //模板

    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static void sendSms(String mobile,String urgentName,String name,String omen,String phone) throws Exception {

        Map<String,Object> params = new HashMap<>();
        params.put("urgentName",urgentName);
        params.put("name",name);
        params.put("omen",omen);
        params.put("phone",phone);

        Client client = SmsUtils.createClient(accessKeyId,accessKeySecret);

        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName(smsSignName)
                .setTemplateCode(templateCode)
                .setPhoneNumbers(mobile)
                .setTemplateParam(JSONObject.toJSONString(params));
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse response = client.sendSmsWithOptions(sendSmsRequest, runtime);
            log.info("请求成功:{}",response.body.message);
        } catch (TeaException e) {
            // 如有需要，请打印 error
            log.info("发送失败:{}",com.aliyun.teautil.Common.assertAsString(e.message));
        } catch (Exception e) {
            TeaException error = new TeaException(e.getMessage(), e);
            // 如有需要，请打印 error
            log.info("发送失败:{}", com.aliyun.teautil.Common.assertAsString(error.message));
        }
    }
}
